package module
{
	import core.Global;
	
	import events.Msg_FileDownload;
	import events.Msg_LoadResource;
	
	import flash.display.MovieClip;
	import flash.utils.Dictionary;
	
	import interfaces.IMsgListener;
	
	public class ResourceManager implements IMsgListener
	{
		private static var MSG_TABLE:Array = [
			 Msg_LoadResource.M_LOADRESOURCE,
			 Msg_FileDownload.M_FILEDOWNLOAD,
		];
		
		protected var m_resources:Dictionary;			// 资源表
		protected var m_requests:Dictionary;
		
		public function ResourceManager()
		{
			m_resources = new Dictionary(true);
			m_requests = new Dictionary(true);
			Global.addListeners(MSG_TABLE,this);
		}
		
		public function msgManager(e:*=null):void
		{
			switch( e.data.msgid)
			{
				case Msg_LoadResource.M_LOADRESOURCE:
					onLoadedResurce(e.data);
					break;
				case Msg_FileDownload.M_FILEDOWNLOAD:
					onFileLoaded(e.data);
					break;
			}
		}
		
		private function onLoadedResurce(msg:Msg_LoadResource):void
		{
			var res:Array = m_resources[msg.url];
			if (msg.atom == null)
				msg.atom = new Atom(msg.cls);
			else {
				msg.atom.clear();
			}			
			
			if (!res) {
				var reqtable:Array = m_requests[msg.url];
				if (reqtable)
					reqtable.push(msg.atom);
				else {
					Global.loadSwf(msg.url);
					reqtable = new Array();
					reqtable.push(msg.atom);
					m_requests[msg.url] = reqtable;
				}
			}else {
				var cls:Class = res[0].applicationDomain.getDefinition(msg.cls);
				if(cls)
					msg.atom.obj = new cls();
			}
			
			
		}
		
		private function onFileLoaded(msg:Msg_FileDownload):void
		{
			var reqtable:Array = m_requests[msg.url];
			var i:int;
			var atom:Atom = null;
		
			trace(reqtable,"req............");
			// 资源下载失败，清空该资源的申请表
			if (!msg.ok) {
				Global.loadSwf(msg.url);
				return;
			}
			
			// 添加到资源表中
			var res:Array = new Array();
			
			res.push(msg.loader.contentLoaderInfo);
			m_resources[msg.url] = res;
			
			// 通知各个资源对象资源已经可以使用了
			if(reqtable && reqtable.length > 0)
			for (i = 0; i < reqtable.length; i++) {
				atom = reqtable[i];
				var clsref:* = msg.loader.contentLoaderInfo.applicationDomain.getDefinition(atom.cls);
				if (clsref)
					atom.obj = new clsref();
			}	
			
			delete m_requests[msg.url];
			
		}
	}
}